<?php
/**
 * Created by PhpStorm.
 * User: jaylen
 * Date: 2020-04-18
 * Time: 11:08
 */

namespace app\common\validate;


use think\File;

class UploadFile extends BaseValidate
{
    public function __construct()
    {
        parent::__construct();

        // 获取后台配置的最大文件大小
        $file_size = get_system_config('site_file_max_size', 2048) * 1024;

        $this->rule = [
            'file' => 'checkFile|fileSize:'.(string)($file_size).'|fileExt:jpeg,jpg,png,gif,ico',
            'type' => 'require',
            'dir_name' => 'require',
            'category_id' => 'require|number',
        ];

        $this->message = [
            'file.checkFile' => '上传的必须是文件',
            'file.fileSize' => '文件不能超过'.format_bytes($file_size),
            'file.fileExt' => '必须是jpeg,jog,png,gif,ico格式的图片',
            'type.require' => '上传的类型不能为空',
            'dir_name.require' => '上传所保存的文件夹不能为空',
            'category_id.require' => '图集所属栏目不能为空',
            'category_id.number' => '图集所属栏目格式不正确'
        ];

        $this->scene = [
            'image_list' => ['file','category_id'],
            'image' => ['file','type','dir_name']
        ];
    }

    // file验证场景
    public function sceneFile()
    {
        return $this->only(['file','type','dir_name'])
            ->remove('file','fileExt')
            ->append('file','fileExt:zip,rar,7z,doc,docx,xls,xlsx,ppt,pptx,pdf,txt');
    }

    /**
     * 文件验证，兼顾多文件
     * @param $value
     * @param $rule
     * @param $data
     * @return bool
     */
    public function checkFile($value, $rule, $data)
    {

        if (is_array($value)) {
            foreach ($value as $item) {
                if (!$item instanceof File) {
                    return false ;
                }
            }
        } else {
            if (!$value instanceof File) {
                return false;
            }
        }

        return true;
    }
}